//
//  UIImageView+DDGifImageView.m
//  GifBrowser
//
//  Created by 栋栋 施 on 15/8/25.
//  Copyright (c) 2015年 栋栋 施. All rights reserved.
//

#import "UIImageView+DDGifImageView.h"
#import <ImageIO/ImageIO.h>
#import <QuartzCore/CoreAnimation.h>

@interface UIImageView ()
{
    NSMutableArray *frames;
    NSMutableArray *frameDelayTimes;
    CGFloat totalTime;         // 秒数
    CGFloat width;
    CGFloat height;
}

@end

void getFrameInfo(CFURLRef url, NSMutableArray *frames, NSMutableArray *delayTimes, CGFloat *totalTime,CGFloat *gifWidth, CGFloat *gifHeight)
{
    CGImageSourceRef gifSource = CGImageSourceCreateWithURL(url, NULL);
    
    // 或者帧数控制
    size_t frameCount = CGImageSourceGetCount(gifSource);
    for (size_t i = 0; i < frameCount; ++i) {
        // get each frame
        CGImageRef frame = CGImageSourceCreateImageAtIndex(gifSource, i, NULL);
        [frames addObject:(__bridge id)frame];
        CGImageRelease(frame);
        
        // 获取Gif的每一帧的数据
        NSDictionary *dict = (NSDictionary*)CFBridgingRelease(CGImageSourceCopyPropertiesAtIndex(gifSource, i, NULL));
        NSLog(@"kCGImagePropertyGIFDictionary %@", [dict valueForKey:(NSString*)kCGImagePropertyGIFDictionary]);
        
        // 获取GIf的size
        if (gifWidth != NULL && gifHeight != NULL) {
            *gifWidth = [[dict valueForKey:(NSString*)kCGImagePropertyPixelWidth] floatValue];
            *gifHeight = [[dict valueForKey:(NSString*)kCGImagePropertyPixelHeight] floatValue];
        }
        
        NSDictionary *gifDict = [dict valueForKey:(NSString*)kCGImagePropertyGIFDictionary];
        [delayTimes addObject:[gifDict valueForKey:(NSString*)kCGImagePropertyGIFDelayTime]];
        
        if (totalTime) {
            *totalTime = *totalTime + [[gifDict valueForKey:(NSString*)kCGImagePropertyGIFDelayTime] floatValue];
        }
        CFRelease((__bridge CFTypeRef)(dict));
    }
    if (gifSource) {
        CFRelease(gifSource);
    }
}




@implementation UIImageView (DDGifImageView)

#pragma mark -
#pragma mark Init

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    
    if (self)
    {
        frames = [[NSMutableArray alloc] init];
        frameDelayTimes = [[NSMutableArray alloc] init];
    }
    return self;
}

- (instancetype)init
{
    self = [super init];
    if (self)
    {
        frames = [[NSMutableArray alloc] init];
        frameDelayTimes = [[NSMutableArray alloc] init];
    }
    return self;
}

- (instancetype)initWithCoder:(NSCoder *)aDecoder
{
    self = [super initWithCoder:aDecoder];
    
    if (self)
    {
        frames = [[NSMutableArray alloc] init];
        frameDelayTimes = [[NSMutableArray alloc] init];
    }
    return self;
}


- (void)dd_startGif
{
    CAKeyframeAnimation *animation = [CAKeyframeAnimation animationWithKeyPath:@"contents"];
    NSUInteger count = frameDelayTimes.count;
    NSMutableArray *times = [NSMutableArray arrayWithCapacity:count];
    CGFloat currentTime = 0;
    for (NSUInteger i = 0; i < count; ++i) {
        [times addObject:[NSNumber numberWithFloat:(currentTime / totalTime)]];
        currentTime += [[frameDelayTimes objectAtIndex:i] floatValue];
    }
    [animation setKeyTimes:times];
    
    NSMutableArray *images = [NSMutableArray arrayWithCapacity:3];
    for (NSUInteger i = 0; i < count; ++i) {
        [images addObject:[frames objectAtIndex:i]];
    }
    
    [animation setValues:images];
    [animation setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear]];
    animation.duration = totalTime;
    animation.delegate = self;
    animation.repeatCount = GID_MAX;
    
    [self.layer addAnimation:animation forKey:@"gifAnimation"];
}


- (void)dd_stopGif
{
    [self.layer removeAllAnimations];
}

- (void)dd_setLocalFileGifURL:(NSURL *)fileURL
{
    getFrameInfo((__bridge CFURLRef)fileURL, frames, frameDelayTimes, &totalTime, &width, &height);
}

@end
